import React, { Component } from 'react';
import { connect } from 'react-redux';
import { messages } from "share/common";
import errorMessage from "share/errorMessage";
import { Button, Checkbox, Form, Switch, Radio, Input, InputNumber, message } from "antd";
import Priority from "components/template/priority";
import Chooser from "components/chooser";
import { LanguageInput } from "components/template";
import beepTimerService from '../beep-timer.service'

const FormItem = Form.Item;

@Form.create()
@connect(mapStateToProps)
class NoFinanceApproverNotice extends Component {

  state = {
    loading: false,
    isNoticeEntity: false,
  };

  componentDidMount() {
    const { data } = this.props;
    if (data && JSON.parse(data.params || '{}').noticeEntity) {
      this.setState({ isNoticeEntity: true })
    }
  }

  priority = {
    levelCode: 'TENANT',
    levelOrgName: this.props.tenant.tenantName,
    levelOrgId: this.props.tenant.id
  }

  handleSave = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { data } = this.props;
        const { isNoticeEntity } = this.state;
        if (!values.systemAdmins && !isNoticeEntity) {
          message.error(messages('basic-13.key203')/*请选择提醒对象*/);
          return;
        }
        if (isNoticeEntity && (!values.noticeEntity || values.noticeEntity.length === 0)) {
          message.error(messages('basic-13.key204')/*请选择提醒对象的指定人员*/);
          return;
        }
        let remindParams = {
          remindDay: values.remindDay,
          systemAdmins: values.systemAdmins,
          noticeEntity: isNoticeEntity ? values.noticeEntity[0].userOID : '',
        };
        let params = {
          enabledFlag: values.enabledFlag,
          tenantID: values.priority.levelOrgId,
          hour: 3,
          code: 'NoFinanceApproverNoticeTask',
          params: JSON.stringify(remindParams)
        };
        data.id && (params.id = data.id);
        this.setState({ loading: true });
        beepTimerService.newBeepTimer(params).then(() => {
          message.success(messages('common.operate.success')/*操作成功*/)
          this.setState({ loading: false });
          this.props.close(true);
        }).catch(e => {
          errorMessage(e.response);
          this.setState({ loading: false });
        })
      }
    })
  };

  render() {
    const { form: { getFieldDecorator }, data } = this.props;
    const { loading, isNoticeEntity } = this.state;
    const dataParams = JSON.parse(data.params || '{}');
    return (
      <div className="no-finance-approver-detail">
        <Form className="new-form">
          <FormItem label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('enabledFlag', {
              rules: [{ required: true }],
              valuePropName: 'checked',
              initialValue: data.id ? data.enabledFlag : true
            })(
              <Switch />
            )}
          </FormItem>
          <FormItem label={messages('basic-13.key9')/*所属组织*/}>
            {getFieldDecorator('priority', {
              rules: [{ required: true }],
              initialValue: this.priority
            })(
              <Priority
                defaultValue={this.priority}
                showLabel={false}
                top="TENANT"
                onlyTenant
                disabled
                required
              />
            )}
          </FormItem>
          <div className="sub-title">{messages('basic-13.key12')/*提醒对象*/}</div>
          <FormItem label={messages('basic-13.key12')/*提醒对象*/}>
            {getFieldDecorator('systemAdmins', {
              rules: [{ required: true }],
              valuePropName: 'checked',
              initialValue: data.id ? dataParams.systemAdmins : true
            })(
              <Checkbox>{messages('basic-13.key13')/*全租户权限的超级管理员角色*/}</Checkbox>
            )}
          </FormItem>
          <FormItem label=" ">
            <Checkbox
              checked={isNoticeEntity}
              onChange={e => this.setState({ isNoticeEntity: e.target.checked })}
            >
              {messages('basic-13.key14')/*指定人员*/}
            </Checkbox>
            <br/>
            {getFieldDecorator('noticeEntity', {
              initialValue: dataParams.noticeEntity ?
                [{ userOID: dataParams.noticeEntity, fullName: dataParams.noticeName }] : []
            })(
              <Chooser
                type="user"
                valueKey="userOID"
                labelKey="fullName"
                placeholder={messages('common.select')/*请选择*/}
                single
              />
            )}
          </FormItem>
          <div className="sub-title">{messages('basic-13.key15')/*消息内容*/}</div>
          <FormItem label={<span className="ant-form-item-required">{messages('basic-13.key16')/*消息标题*/}</span>}>
            <LanguageInput
              disabled
              buttonDisabled
              value={messages('basic-13.key205')/*审核人配置提醒*/}
            />
          </FormItem>
          <FormItem label={<span className="ant-form-item-required">{messages('basic-13.key17')/*消息正文*/}</span>}>
            <LanguageInput
              textArea
              disabled
              buttonDisabled
              value={`${messages('basic-13.key206')/*您好，以下单据审批通过时间在#开始时间#到#结束时间#之间，未找到对应的单据审核人，请查看并及时维护对应的财务审核人员，避免影响单据处理进度。*/}\n\n#${messages('basic-13.key207')/*单据明细列表*/}#`}
            />
          </FormItem>
          <div className="sub-title">{messages('basic-13.key18')/*消息触发*/}</div>
          <FormItem label={<span className="ant-form-item-required">{messages('basic-13.key85')/*提醒类型*/}</span>}>
            <Radio defaultChecked disabled>{messages('basic-13.key208')/*每日提醒*/}</Radio>
          </FormItem>
          <FormItem label={<span className="ant-form-item-required">{messages('basic-13.key35')/*提醒时间*/}</span>}>
            <Input disabled value="03:00"/>
          </FormItem>
          <FormItem label={messages('basic-13.key209')/*提醒单据范围*/}>
            {messages('basic-13.key210')/*单据审批通过时间在提醒日前*/}
            {getFieldDecorator('remindDay', {
              rules: [{
                required: true,
                message: messages('basic-13.key40')/*请输入temp2*/
              }],
              initialValue: data.id ? +dataParams.remindDay : 3
            })(
              <InputNumber step={1} precision={0} min={1} max={30} style={{ width: 80, margin: '0 8px' }}/>
            )}
            {messages('basic-13.key211')/*天内的单据*/}
            <div className="ant-form-extra">
              {messages('basic-13.key212')/*例如配置为提醒日前3天内的单据，则1月4日触发的单据是审批通过日期在1月1日00:00到1月3日23:59之间的单据*/}
            </div>
          </FormItem>
        </Form>
        <div className="slide-footer">
          <Button
            type="primary"
            onClick={this.handleSave}
            loading={loading}
          >
            {messages('common.save')/*保存*/}
          </Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps (state) {
  return {
    tenant: state.login.tenant
  };
}

export default NoFinanceApproverNotice;
